﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MusicPlayerPlus.Method.Data
{
    public class Settings
    {
        /// <summary>
        /// 新建配置文件
        /// </summary>
        /// <param name="filename">文件名</param>
        public Settings(string filename = "Settings")
        {
            settingsFileName = filename;
        }
        public readonly string settingsFileName = "Settings";
        /// <summary>
        ///  获取配置
        /// </summary>
        /// <param name="key">Key</param>
        /// <returns></returns>
        public T GetSettings<T>(string key, T defaultVal = default(T))
        {
            try
            {
                Dictionary<string, string> settings = SettingsData();
                if (settings.ContainsKey(key))
                {
                    string valjson = settings[key];
                    T val = Helper.JsonHelper.Deserialize<T>(valjson);
                    return val;
                }
                return defaultVal;
            }
            catch (Exception)
            {
                return defaultVal;
            }
        }
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="val">Value</param>
        /// <returns>是否保存成功</returns>
        public bool SaveSettings<T>(string key, T val)
        {
            try
            {
                string val_Json = Helper.JsonHelper.Serialize(val);//先把数据转成Json再存到Dictionary
                Dictionary<string, string> settings = SettingsData();
                if (settings.ContainsKey(key))
                {
                    settings[key] = val_Json;
                }
                else
                {
                    settings.Add(key, val_Json);
                }
                string data = Helper.JsonHelper.Serialize(settings);
                LocaData.SaveData(settingsFileName, data);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, string> SettingsData()
        {
            string data = LocaData.ReadData(settingsFileName);
            if (string.IsNullOrEmpty(data))
            {
                return new Dictionary<string, string>();
            }
            Dictionary<string, string> settings = Helper.JsonHelper.Deserialize<Dictionary<string, string>>(data);
            if (settings == null)
            {
                settings = new Dictionary<string, string>();
            }
            return settings;
        }
    }
}
